<template>
	<view>
		<view style="background: white;padding: 20rpx;">
			<view class="flex align" style="margin-bottom: 10rpx;" v-if="type==''">
				<view class="input-sel flex align" @click="show = true">
					<input placeholder="点击选择商家" disabled v-model="store_name" />
					<uni-icons type="down" size="20" color="gainsboro"></uni-icons>
				</view>
				<view class="reset" @click="toReset">重置</view>
			</view>
			<uni-datetime-picker @change="changeDate" v-model="range" type="daterange" />
		</view>
		<view class="nums flex align between">总支出：{{money}}￥
		<view class="reset" @click="toExcel">表格导出</view>
		</view>
		<view class="list flex align between" v-for="(item,index) in list" :key="index">
			<image src="../../static/images/icon.png" style="width: 52rpx;height: 52rpx;"></image>
			<view class="names">
				<view>{{item.remark}}</view>
				<view>商户：{{item.store_name}}</view>
				<view>时间：{{item.create_time}}</view>
			</view>
			<view class="price">{{item.money}}￥</view>
		</view>
		<uni-load-more :status="status" v-if="!empty" :content-text="loadText"></uni-load-more>
		<xw-empty :isShow="empty" text="暂无数据" textColor="#777777"></xw-empty>
		<u-picker :show="show" :columns="columns" keyName="name" @cancel="show = false" @confirm="onConfirm"></u-picker>
	</view>
</template>

<script>
	import {
		storeMoneyList,
		storeList
	} from '@/api/apiData.js';
	export default {
		data() {
			return {
				range: '',
				start_time: '',
				end_time: '',
				totalPage: 1,
				page: 0,
				offset: 20,
				list: [],
				scrollTop: 0,
				empty: false,
				loadText: {
					loadmore: '点击或上拉加载更多',
					loading: '努力加载中',
					nomore: '实在没有了'
				},
				status: 'loadmore',
				create_time: [],
				store_id: '',
				money: '',
				show: false,
				columns: [],
				store_name: '',
				type: ''
			};
		},
		onLoad(option) {
			if (option.id) {
				this.store_id = option.id
				this.type = 1
			}
			this.getlist()
			this.getStore()
		},
		onPageScroll(e) {
			const that = this;
			that.scrollTop = e.scrollTop;
		},
		onReachBottom() {
			const that = this;
			that.getlist();
		},
		methods: {
			toExcel() {
				// uni.navigateTo({
				// 	url:'/pages/manage/table'
				// })
				// console.log(this.list)
				let list = this.list
				let arr = []
				list.forEach(item => {
					arr.push({
						name: item.store_name,
						type_text: item.type_text,
						money: item.money,
						remark: item.remark,
						create_time: item.create_time,
					})
				})
				this.tableToExcel(arr)
			},
			uuid() {
				// 创建一个新的Date对象，表示当前时间
				var currentDate = new Date();

				// 获取年、月、日、小时、分钟和秒
				var year = currentDate.getFullYear();
				var month = (currentDate.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，所以要加1，并补零
				var day = currentDate.getDate().toString().padStart(2, '0'); // 补零
				var hours = currentDate.getHours().toString().padStart(2, '0'); // 补零
				var minutes = currentDate.getMinutes().toString().padStart(2, '0'); // 补零
				var seconds = currentDate.getSeconds().toString().padStart(2, '0'); // 补零

				// 拼接日期和时间字符串
				var formattedDateTime = year + month + day + hours + minutes + seconds;
				return formattedDateTime
				console.log(formattedDateTime); // 输出：2023-11-02 05:51:15
				// return 'xxx-xxx-xxx'.replace(/[xy]/g, c => {
				// 	var r = Math.random() * 16 | 0,
				// 		v = c == 'x' ? r : (r & 0x3 | 0x8)
				// 	return v.toString(16)
				// })
			},

			tableToExcel(arr) {
				// 要导出的json数据
				// const jsonData = [{
				// 		name: '科比',
				// 		phone: '123456',
				// 		email: '科比@163.com'
				// 	},
				// 	{
				// 		name: '科比',
				// 		phone: '123456',
				// 		email: '科比@163.com'
				// 	},
				// 	{
				// 		name: '科比',
				// 		phone: '123456',
				// 		email: '科比@163.com'
				// 	},
				// 	{
				// 		name: '科比',
				// 		phone: '123456',
				// 		email: '科比@163.com'
				// 	},
				// ]
				const jsonData = arr
				// 列标题
				let worksheet = 'sht1'
				let str =
					'<tr><td style="color:red">总支出：' + this.money +
					'</td></tr><tr><td style="text-align: center">商户</td><td style="text-align: center">类型</td><td style="text-align: center">支出金额</td><td style="text-align: center">备注</td><td style="text-align: center">时间</td></tr>'
				// 循环遍历，每行加入tr标签，每个单元格加td标签
				for (let i = 0; i < jsonData.length; i++) {
					str += '<tr>'
					for (let item in jsonData[i]) {
						// 增加\t为了不让表格显示科学计数法或者其他格式
						str += `<td>${jsonData[i][item] + '\t'}</td>`
					}
					str += '</tr>'
				}
				// 下载的表格模板数据

				let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" 
			xmlns:x="urn:schemas-microsoft-com:office:excel" 
			xmlns="http://www.w3.org/TR/REC-html40">
			<head><!--[if gte mso 9]><xml encoding="UTF-8"><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
			<x:Name>${worksheet}</x:Name>
			<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
			</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
			</head><body><table>${str}</table></body></html>`
				// 下载模板
				// #ifdef APP-PLUS
				this.appExportFile(template)
				// #endif
				// 下载模板
				// #ifdef MP-WEIXIN
				this.wxExportFile(template)
				// #endif
			},

			// 导出文件到手机 fileData:要写入到文件的数据，返回参数为文档路径
			appExportFile(fileData, documentName = '商户支出统计') {
				// PUBLIC_DOCUMENTS: 程序公用文档目录常量
				plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, fs => {
					let rootObj = fs.root,
						fullPath = rootObj.fullPath
					console.log('开始导出数据********')
					// 创建文件夹
					rootObj.getDirectory(documentName, {
						create: true
					}, dirEntry => {
						// 创建文件,防止重名
						let fileName = 'excel' + this.uuid() + '.xlsx'
						dirEntry.getFile(fileName, {
							create: true
						}, fileEntry => {
							fileEntry.createWriter(writer => {
								writer.onwritestart = res => console.log('正在导出')
								//  /storage/emulated/0指的就是系统路径
								let pathStr = fullPath.replace('/storage/emulated/0', '')
								// 成功导出数据
								writer.onwrite = res => {
									// 文件路径
									let filePath = res.target.fileName
									uni.hideLoading()
									setTimeout(() => {
										console.log('成功导出')
										this.successTip = `文件位置：${filePath}`

										uni.openDocument({
											filePath,
											success: res => console
												.log('打开文档成功'),
											fail: err => console.log(
												err)
										})
									}, 500)
								}
								// 写入内容
								writer.write(fileData)
							}, err => console.log(err.message))
						})
					})
				})
			},

			wxExportFile(template, documentName = '商户支出统计') {
				const fs = uni.getFileSystemManager()
				// 创建文件名字, 防止重名
				let filePath = uni.env.USER_DATA_PATH + '/' + (documentName + this.uuid()) + '.xls'
				fs.writeFile({
					filePath,
					data: template,
					encoding: 'utf8',
					success: res => {

						uni.openDocument({
							filePath,
							showMenu: true, //是否显示右上角菜单
							success: res => console.log('打开文档成功。文件位置', filePath),
							fail: err => console.log(err)
						})
					},
					fail: err => console.info(err)
				})
			},
			toReset() {
				this.store_id = ''
				this.store_name = ''
				this.start_time = ''
				this.end_time = ''
				this.create_time = []
				this.range = ''
				this.page = 0
				this.list = []
				this.getlist();
			},
			onConfirm(e) {
				this.store_id = e.value[0].id
				this.store_name = e.value[0].name
				this.show = false
				this.page = 0
				this.list = []
				this.getlist();
			},
			async getStore() {
				let result = await storeList({
					page: 1,
					size: 40
				});
				if (result.code == 1) {
					this.columns = [result.data.list]
				}
			},
			changeDate(e) {
				console.log(e)
				if (e.length == 0) {
					this.start_time = ''
					this.end_time = ''
					this.create_time = []
				} else {
					this.start_time = e[0]
					this.end_time = e[1]
					this.create_time = [this.start_time, this.end_time]
				}
				this.page = 0
				this.list = []
				this.getlist();
			},
			async getlist() {
				const that = this;
				const {
					totalPage,
					page,
					offset,
					list,
					create_time,
					store_id
				} = that;
				let obj = {
					size: offset,
					page: page + 1,
					create_time,
					store_id
				};
				that.status = 'loading';
				if (totalPage > page) {
					let result = await storeMoneyList(obj);
					if (result.code == 1) {
						that.money = result.data.money
						that.page = page + 1;
						if (result.data.total == 0) {
							console.log((888))
							that.empty = true;
							that.status = 'nomore';
							return;
						}
						that.empty = false;
						setTimeout(() => {
							that.status = 'loadmore';
						}, 500);
						that.list = list.concat(result.data.list);
						that.totalPage = Math.ceil(result.data.total / offset);
					}
				} else {
					setTimeout(() => {
						that.status = 'nomore';
					}, 500);
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.reset {
		margin-left: 20rpx;
		color: #FF2937;
		border: solid 1rpx;
		padding: 10rpx 20rpx;
		font-size: 26rpx;
	}

	.input-sel {
		border: solid 1rpx gainsboro;
		padding: 10rpx 20rpx;
		width: 50%;

		input {
			font-size: 30rpx;
		}
	}

	.nums {
		padding: 24rpx 36rpx 0;
		font-size: 30rpx;
		color: #FF2937;
	}

	.list {
		background: white;
		padding: 24rpx 36rpx;
		margin: 25rpx;

		.names {
			width: 70%;
			color: #C0C0C0;
			font-size: 18rpx;

			view:nth-child(1) {
				font-size: 22rpx;
				color: #333333;
			}

			// view:nth-child(2) {
			// 	color: #C0C0C0;
			// 	font-size: 18rpx;
			// }
		}

		.price {
			color: #FF2937;
			font-size: 26rpx;
			font-weight: bold;
		}
	}
</style>